package aspectj;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.aspectj.lang.Signature;

import com.opensymphony.xwork2.ActionSupport;
import com.redhat.auth.exception.BusinessException;
import com.redhat.auth.exception.RedworkException;
import com.redhat.auth.exception.RedworkExceptionResultType;
import com.redhat.auth.exception.WebErrUtil;


/**
 * Exception的拦截代码，对定义了RedworkException标签的方法进行拦截，进行异常处理
 * @author lingen.liu
 *
 */
public aspect RedworkExcepitonAspectJ {
	

	/**
	 * 所有拦截只针对action,也就是继承了ActionSupport的类，并且针对标注了RedworkException的方法进行拦截
	 */
	
	public pointcut actionMethod():
	     //execution(public String com.csair.lps.web.flightschedule.FlightScheduleAction.update());
	     execution(@RedworkException * *(..));
	
    String around():actionMethod(){
    	Object result = null;
    	try{
    		result = proceed();
    	}catch(Exception e){
    		try{
    		ActionSupport thisAction = (ActionSupport)(thisJoinPoint.getThis());
    		Class actionClass = thisJoinPoint.getThis().getClass();
    		Signature meth = thisJoinPoint.getSignature();
    		String methodName = meth.getName();
    		Method actionMe = actionClass.getMethod(methodName, null);
    		Annotation[] thisAnnotations =  actionMe.getAnnotations();
    		RedworkException redworkExceptionAnnotation = null;
    		for(Annotation annotation:thisAnnotations){
    			if(annotation instanceof RedworkException){
    				redworkExceptionAnnotation = (RedworkException)annotation;
    				break;
    			}
    		}
    		//获取RedworkException标签中定义的提醒类型
    		RedworkExceptionResultType type = redworkExceptionAnnotation.returnType();
    		String errorCode = redworkExceptionAnnotation.defaultErrorCode();
    		String errorPage = redworkExceptionAnnotation.defaultErrorPage();
    		if(e instanceof BusinessException){
    			errorCode = e.getMessage();
    		}
    		if(type.equals(RedworkExceptionResultType.ALERT))WebErrUtil.buildAlertErrToPage(thisAction, errorCode);
    		if(type.equals(RedworkExceptionResultType.PAGE))WebErrUtil.buildErrToPage(thisAction, errorPage, errorCode);
    		}catch(Exception innere){
    			innere.printStackTrace();
    		}
    	}
		return (String)result;
	}
}
